<template>
  <div class="ticket-orders">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>门票订单</span>
          <div class="header-actions">
            <el-button type="success" @click="exportOrders">导出订单</el-button>
          </div>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="订单号">
          <el-input
            v-model="searchForm.orderNo"
            placeholder="请输入订单号"
            clearable
          />
        </el-form-item>
        <el-form-item label="景点名称">
          <el-input
            v-model="searchForm.spotName"
            placeholder="请输入景点名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="下单时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option label="待支付" value="pending" />
            <el-option label="已支付" value="paid" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
            <el-option label="已退款" value="refunded" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="sortedOrderList"
        @sort-change="handleSortChange"
        style="width: 100%"
      >
        <el-table-column prop="orderNo" label="订单编号" width="180" />
        <el-table-column
          prop="productName"
          label="商品名称"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column
          prop="totalAmount"
          label="订单金额"
          width="120"
          sortable="custom"
        >
          <template #default="{ row }">
            ¥{{ row.totalAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="下单时间"
          width="160"
          sortable="custom"
        />
        <el-table-column
          prop="payTime"
          label="支付时间"
          width="160"
          sortable="custom"
        />
        <el-table-column prop="status" label="订单状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button type="primary" size="small" @click="showDetail(row)">
                详情
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
        
        <template #empty>
          <div class="empty-state">
            <el-empty 
              description="暂无订单数据" 
              :image-size="200"
            >
              <div class="empty-text">还没有任何门票订单</div>
              <div class="empty-subtext">用户下单后即可在此处查看订单信息</div>
            </el-empty>
          </div>
        </template>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 订单详情对话框 -->
      <el-dialog
        v-model="detailVisible"
        title="订单详情"
        width="800px"
        :append-to-body="true"
        :modal-class="'order-detail-modal'"
        :lock-scroll="true"
        destroy-on-close
      >
        <el-scrollbar height="calc(90vh - 200px)">
          <div class="order-detail">
            <!-- 基本信息 -->
            <div class="detail-section">
              <h4 class="section-title">基本信息</h4>
              <el-descriptions :column="2" border>
                <el-descriptions-item label="订单号">{{
                  currentOrder.orderNo
                }}</el-descriptions-item>
                <el-descriptions-item label="下单时间">{{
                  currentOrder.createTime
                }}</el-descriptions-item>
                <el-descriptions-item label="订单状态">
                  <el-tag :type="getStatusType(currentOrder.status)">
                    {{ getStatusLabel(currentOrder.status) }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="支付方式">{{
                  currentOrder.paymentMethod
                }}</el-descriptions-item>
                <el-descriptions-item
                  label="支付时间"
                  v-if="currentOrder.payTime"
                  >{{ currentOrder.payTime }}</el-descriptions-item
                >
                <el-descriptions-item
                  label="支付流水号"
                  v-if="currentOrder.paymentNo"
                  >{{ currentOrder.paymentNo }}</el-descriptions-item
                >
              </el-descriptions>
            </div>

            <!-- 景点信息 -->
            <div class="detail-section">
              <h4 class="section-title">景点信息</h4>
              <el-descriptions :column="1" border>
                <el-descriptions-item label="景点名称">
                  <div class="spot-detail-info">
                    <el-image
                      v-if="currentOrder.spotImage"
                      :src="currentOrder.spotImage"
                      fit="cover"
                      class="spot-detail-image"
                    />
                    <div class="spot-detail-content">
                      <div class="spot-name">{{ currentOrder.spotName }}</div>
                      <div class="spot-address" v-if="currentOrder.spotAddress">
                        <el-icon><Location /></el-icon>
                        {{ currentOrder.spotAddress }}
                      </div>
                    </div>
                  </div>
                </el-descriptions-item>
                <el-descriptions-item label="门票类型">{{
                  currentOrder.ticketType
                }}</el-descriptions-item>
                <el-descriptions-item label="游玩日期">{{
                  currentOrder.visitDate
                }}</el-descriptions-item>
                <el-descriptions-item label="购买数量"
                  >{{ currentOrder.quantity }}张</el-descriptions-item
                >
                <el-descriptions-item label="单价"
                  >￥{{ currentOrder.price }}</el-descriptions-item
                >
                <el-descriptions-item label="总金额"
                  >￥{{ currentOrder.totalAmount }}</el-descriptions-item
                >
              </el-descriptions>
            </div>

            <!-- 游客信息 -->
            <div class="detail-section">
              <h4 class="section-title">游客信息</h4>
              <el-descriptions :column="2" border>
                <el-descriptions-item label="联系人">{{
                  currentOrder.contactName
                }}</el-descriptions-item>
                <el-descriptions-item label="手机号">{{
                  currentOrder.contactPhone
                }}</el-descriptions-item>
                <el-descriptions-item label="身份证号" :span="2">{{
                  currentOrder.idCard
                }}</el-descriptions-item>
              </el-descriptions>
              <div class="visitors-list" v-if="currentOrder.visitors?.length">
                <h5>游客列表</h5>
                <el-table :data="currentOrder.visitors" border stripe>
                  <el-table-column prop="name" label="姓名" />
                  <el-table-column prop="idCard" label="身份证号" />
                  <el-table-column prop="phone" label="手机号" />
                  <el-table-column prop="ticketStatus" label="验票状态">
                    <template #default="{ row }">
                      <el-tag :type="getTicketStatusType(row.ticketStatus)">
                        {{ getTicketStatusLabel(row.ticketStatus) }}
                      </el-tag>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>

            <!-- 电子票信息 -->
            <div class="detail-section" v-if="currentOrder.eTickets?.length">
              <h4 class="section-title">电子票信息</h4>
              <div class="e-tickets-list">
                <el-card
                  v-for="(ticket, index) in currentOrder.eTickets"
                  :key="index"
                  class="e-ticket-card"
                >
                  <div class="e-ticket-header">
                    <span class="ticket-no">票号：{{ ticket.ticketNo }}</span>
                    <el-tag :type="getTicketStatusType(ticket.status)">
                      {{ getTicketStatusLabel(ticket.status) }}
                    </el-tag>
                  </div>
                  <div class="e-ticket-qr" v-if="ticket.qrCode">
                    <el-image :src="ticket.qrCode" fit="contain" />
                  </div>
                  <div class="e-ticket-info">
                    <p>验票时间：{{ ticket.checkTime || "未验票" }}</p>
                    <p v-if="ticket.checkLocation">
                      验票地点：{{ ticket.checkLocation }}
                    </p>
                  </div>
                </el-card>
              </div>
            </div>

            <!-- 订单日志 -->
            <div class="detail-section">
              <h4 class="section-title">订单日志</h4>
              <el-timeline>
                <el-timeline-item
                  v-for="(log, index) in currentOrder.orderLogs"
                  :key="index"
                  :timestamp="log.time"
                  :type="getLogType(log.type)"
                >
                  <h4>{{ log.title }}</h4>
                  <p>{{ log.content }}</p>
                  <p class="operator" v-if="log.operator">
                    操作人：{{ log.operator }}
                  </p>
                </el-timeline-item>
              </el-timeline>
            </div>

            <!-- 备注信息 -->
            <div class="detail-section" v-if="currentOrder.remark">
              <h4 class="section-title">备注信息</h4>
              <div class="remark-content">{{ currentOrder.remark }}</div>
            </div>
          </div>
        </el-scrollbar>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="detailVisible = false">关闭</el-button>
            <el-button
              v-if="
                currentOrder.status === 'paid' && !isTicketChecked(currentOrder)
              "
              type="primary"
              @click="handleCheckTicket(currentOrder)"
            >
              验票
            </el-button>
            <el-button
              v-if="currentOrder.status === 'paid'"
              type="success"
              @click="handleComplete(currentOrder)"
            >
              完成订单
            </el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  SortUp,
  SortDown,
  View,
  Check,
  Location,
} from "@element-plus/icons-vue";
import axios from "@/api/axios";
import * as XLSX from "xlsx";

// 搜索表单
const searchForm = reactive({
  orderNo: "",
  spotName: "",
  dateRange: [],
  status: "",
});

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 表格数据
const loading = ref(false);
const orderList = ref([]);

// 排序配置
const sortConfig = reactive({
  prop: "createTime",
  order: "descending",
});

// 获取排序后的数据
const sortedOrderList = computed(() => {
  const list = [...orderList.value];
  if (!sortConfig.prop) return list;

  return list.sort((a, b) => {
    let aValue = a[sortConfig.prop];
    let bValue = b[sortConfig.prop];

    // 处理时间排序
    if (sortConfig.prop === "createTime" || sortConfig.prop === "payTime") {
      aValue = new Date(aValue).getTime();
      bValue = new Date(bValue).getTime();
    }
    // 处理金额排序
    if (sortConfig.prop === "totalAmount") {
      aValue = parseFloat(aValue);
      bValue = parseFloat(bValue);
    }

    if (sortConfig.order === "ascending") {
      return aValue > bValue ? 1 : -1;
    } else {
      return aValue < bValue ? 1 : -1;
    }
  });
});

// 处理排序变化
const handleSortChange = ({ prop, order }) => {
  sortConfig.prop = prop;
  sortConfig.order = order;
  handleSearch();
};

// 获取状态标签
const getStatusLabel = (status) => {
  const statusMap = {
    pending: "待支付",
    paid: "已支付",
    completed: "已完成",
    cancelled: "已取消",
    refunded: "已退款",
  };
  return statusMap[status] || status;
};

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    pending: "warning",
    paid: "success",
    completed: "success",
    cancelled: "info",
    refunded: "danger",
  };
  return typeMap[status] || "info";
};

// 订单详情相关
const detailVisible = ref(false);
const currentOrder = reactive({});

// 显示订单详情
const showDetail = async (row) => {
  try {
    loading.value = true;
    // 获取订单详情
    const response = await axios.get(`/admin/orders/${row.id}`);
    Object.assign(currentOrder, response.data || row);
  } catch (error) {
    console.error("获取订单详情失败：", error);
    // 如果API失败，使用传入的行数据
    Object.assign(currentOrder, row);
  } finally {
    loading.value = false;
    detailVisible.value = true;
  }
};

// 完成订单
const handleComplete = async (row) => {
  try {
    await ElMessageBox.confirm("确认将该订单标记为已完成吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    loading.value = true;
    // 调用完成订单API
    await axios.put(`/admin/orders/${row.id}/complete`);

    ElMessage.success("操作成功");
    detailVisible.value = false;
    fetchData();
  } catch (error) {
    if (error !== "cancel") {
      console.error("完成订单失败：", error);
      ElMessage.error("操作失败，请稍后重试");
    }
  } finally {
    loading.value = false;
  }
};

// 获取数据列表
const fetchData = async () => {
  loading.value = true;
  try {
    // 构建请求参数
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      orderNo: searchForm.orderNo || undefined,
      spotName: searchForm.spotName || undefined,
      status: searchForm.status || undefined,
      startDate: searchForm.dateRange && searchForm.dateRange[0] ? searchForm.dateRange[0] : undefined,
      endDate: searchForm.dateRange && searchForm.dateRange[1] ? searchForm.dateRange[1] : undefined,
      sortField: sortConfig.prop,
      sortOrder: sortConfig.order,
    };

    // 调用API获取数据
    const response = await axios.get("/admin/orders", { params });
    
    // 检查响应是否存在
    if (response) {
      // 不管是否有数据，都使用后端返回的结果
      orderList.value = Array.isArray(response.records) ? response.records : [];
      total.value = response.total || 0;
    } else {
      // 响应对象不存在，设置为空数组
      orderList.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error("获取订单列表失败：", error);
    ElMessage.error("获取数据失败");
    
    orderList.value = [
      {
        id: 1,
        orderNo: "T20240315001",
        productName: "贵港园博园门票",
        spotName: "贵港园博园",
        spotImage: "https://example.com/spots/yuanboyuan.jpg",
        spotAddress: "贵港市港北区港城大道168号",
        ticketType: "成人票",
        quantity: 2,
        price: 80,
        totalAmount: 160,
        createTime: "2024-03-15 10:30:00",
        payTime: "2024-03-15 10:35:00",
        visitDate: "2024-03-20",
        status: "paid",
        contactName: "张三",
        contactPhone: "13800138000",
        idCard: "450800199001010001",
        paymentMethod: "微信支付",
        paymentNo: "wx20240315103510001",
        remark: "需要导游讲解服务",
        visitors: [
          {
            name: "张三",
            idCard: "450800199001010001",
            phone: "13800138000",
            ticketStatus: "unused"
          },
          {
            name: "李四",
            idCard: "450800199101020002",
            phone: "13900139000",
            ticketStatus: "unused"
          }
        ],
        eTickets: [
          {
            ticketNo: "ET20240315001001",
            status: "unused",
            qrCode: "https://example.com/qrcode/et001.png",
            checkTime: "",
            checkLocation: ""
          },
          {
            ticketNo: "ET20240315001002",
            status: "unused",
            qrCode: "https://example.com/qrcode/et002.png",
            checkTime: "",
            checkLocation: ""
          }
        ],
        orderLogs: [
          {
            time: "2024-03-15 10:30:00",
            title: "订单创建",
            content: "用户创建订单",
            type: "user"
          },
          {
            time: "2024-03-15 10:35:00",
            title: "订单支付",
            content: "用户通过微信支付完成支付",
            type: "user"
          }
        ]
      },
      {
        id: 2,
        orderNo: "T20240314002",
        productName: "贵港市博物馆特展门票",
        spotName: "贵港市博物馆",
        spotImage: "https://example.com/spots/museum.jpg",
        spotAddress: "贵港市港北区桂平路88号",
        ticketType: "家庭票(2大1小)",
        quantity: 1,
        price: 120,
        totalAmount: 120,
        createTime: "2024-03-14 15:20:00",
        payTime: "2024-03-14 15:22:00",
        visitDate: "2024-03-18",
        status: "completed",
        contactName: "王五",
        contactPhone: "13700137000",
        idCard: "450800198805050003",
        paymentMethod: "支付宝",
        paymentNo: "zfb20240314152200001",
        visitors: [
          {
            name: "王五",
            idCard: "450800198805050003",
            phone: "13700137000",
            ticketStatus: "used"
          },
          {
            name: "赵六",
            idCard: "450800198710100004",
            phone: "13600136000",
            ticketStatus: "used"
          },
          {
            name: "小明",
            idCard: "450800201201010005",
            phone: "",
            ticketStatus: "used"
          }
        ],
        eTickets: [
          {
            ticketNo: "ET20240314002001",
            status: "used",
            qrCode: "https://example.com/qrcode/et003.png",
            checkTime: "2024-03-18 10:15:30",
            checkLocation: "贵港市博物馆东门入口"
          }
        ],
        orderLogs: [
          {
            time: "2024-03-14 15:20:00",
            title: "订单创建",
            content: "用户创建订单",
            type: "user"
          },
          {
            time: "2024-03-14 15:22:00",
            title: "订单支付",
            content: "用户通过支付宝完成支付",
            type: "user"
          },
          {
            time: "2024-03-18 10:15:30",
            title: "验票通过",
            content: "用户门票已验证通过",
            type: "system"
          },
          {
            time: "2024-03-18 16:30:00",
            title: "订单完成",
            content: "订单已自动完成",
            type: "system"
          }
        ]
      },
      {
        id: 3,
        orderNo: "T20240310003",
        productName: "贵港石蟆风景区门票",
        spotName: "石蟆风景区",
        spotImage: "https://example.com/spots/shimatou.jpg",
        spotAddress: "贵港市港南区石蟆乡",
        ticketType: "学生票",
        quantity: 3,
        price: 45,
        totalAmount: 135,
        createTime: "2024-03-10 09:15:00",
        payTime: "2024-03-10 09:16:30",
        visitDate: "2024-03-12",
        status: "refunded",
        contactName: "陈一",
        contactPhone: "13500135000",
        idCard: "450800200005050006",
        paymentMethod: "微信支付",
        paymentNo: "wx20240310091630001",
        remark: "因天气原因申请退款",
        visitors: [
          {
            name: "陈一",
            idCard: "450800200005050006",
            phone: "13500135000",
            ticketStatus: "invalid"
          },
          {
            name: "林二",
            idCard: "450800200006060007",
            phone: "13400134000",
            ticketStatus: "invalid"
          },
          {
            name: "黄三",
            idCard: "450800200007070008",
            phone: "13300133000",
            ticketStatus: "invalid"
          }
        ],
        eTickets: [
          {
            ticketNo: "ET20240310003001",
            status: "invalid",
            qrCode: "https://example.com/qrcode/et004.png",
            checkTime: "",
            checkLocation: ""
          },
          {
            ticketNo: "ET20240310003002",
            status: "invalid",
            qrCode: "https://example.com/qrcode/et005.png",
            checkTime: "",
            checkLocation: ""
          },
          {
            ticketNo: "ET20240310003003",
            status: "invalid",
            qrCode: "https://example.com/qrcode/et006.png",
            checkTime: "",
            checkLocation: ""
          }
        ],
        orderLogs: [
          {
            time: "2024-03-10 09:15:00",
            title: "订单创建",
            content: "用户创建订单",
            type: "user"
          },
          {
            time: "2024-03-10 09:16:30",
            title: "订单支付",
            content: "用户通过微信支付完成支付",
            type: "user"
          },
          {
            time: "2024-03-11 16:40:00",
            title: "申请退款",
            content: "用户申请退款，原因：天气原因无法前往",
            type: "user"
          },
          {
            time: "2024-03-11 17:20:00",
            title: "退款审核通过",
            content: "管理员已审核通过退款申请",
            type: "admin",
            operator: "管理员-李明"
          },
          {
            time: "2024-03-11 17:25:00",
            title: "退款完成",
            content: "退款金额135元已原路退回",
            type: "system"
          }
        ]
      },
      {
        id: 4,
        orderNo: "T20240305004",
        productName: "贵港江口码头古镇套票",
        spotName: "江口码头古镇",
        spotImage: "https://example.com/spots/jiangkou.jpg",
        spotAddress: "贵港市覃塘区江口镇",
        ticketType: "VIP体验票",
        quantity: 1,
        price: 198,
        totalAmount: 198,
        createTime: "2024-03-05 14:20:00",
        payTime: "",
        visitDate: "2024-03-08",
        status: "cancelled",
        contactName: "郑七",
        contactPhone: "13200132000",
        idCard: "450800199203030009",
        paymentMethod: "",
        visitors: [
          {
            name: "郑七",
            idCard: "450800199203030009",
            phone: "13200132000",
            ticketStatus: "invalid"
          }
        ],
        orderLogs: [
          {
            time: "2024-03-05 14:20:00",
            title: "订单创建",
            content: "用户创建订单",
            type: "user"
          },
          {
            time: "2024-03-05 14:50:00",
            title: "订单取消",
            content: "用户取消订单",
            type: "user"
          }
        ]
      }
    ];
    total.value = orderList.value.length;
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchData();
};

// 重置搜索
const resetSearch = () => {
  searchForm.orderNo = "";
  searchForm.spotName = "";
  searchForm.dateRange = [];
  searchForm.status = "";
  handleSearch();
};

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchData();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchData();
};

// 导出订单
const exportOrders = () => {
  // 制作导出数据
  const exportData = orderList.value.map(order => {
    return {
      '订单编号': order.orderNo,
      '商品名称': order.productName,
      '订单金额': order.totalAmount,
      '下单时间': order.createTime,
      '支付时间': order.payTime || '-',
      '订单状态': getStatusLabel(order.status),
      '联系人': order.contactName,
      '联系电话': order.contactPhone,
      '支付方式': order.paymentMethod || '-',
      '游玩日期': order.visitDate
    };
  });

  // 创建工作簿
  const worksheet = XLSX.utils.json_to_sheet(exportData);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, "订单数据");
  
  // 设置列宽
  const colWidth = [
    { wch: 15 }, // 订单编号
    { wch: 20 }, // 商品名称
    { wch: 10 }, // 订单金额
    { wch: 20 }, // 下单时间
    { wch: 20 }, // 支付时间
    { wch: 10 }, // 订单状态
    { wch: 10 }, // 联系人
    { wch: 15 }, // 联系电话
    { wch: 10 }, // 支付方式
    { wch: 12 }, // 游玩日期
  ];
  worksheet['!cols'] = colWidth;
  
  // 导出文件
  const now = new Date();
  const fileName = `订单数据_${now.getFullYear()}${(now.getMonth()+1).toString().padStart(2, '0')}${now.getDate().toString().padStart(2, '0')}.xlsx`;
  XLSX.writeFile(workbook, fileName);
  
  ElMessage.success("导出成功");
};

// 获取验票状态标签
const getTicketStatusLabel = (status) => {
  const statusMap = {
    unused: "未使用",
    used: "已使用",
    expired: "已过期",
    invalid: "已作废",
  };
  return statusMap[status] || status;
};

// 获取验票状态类型
const getTicketStatusType = (status) => {
  const typeMap = {
    unused: "primary",
    used: "success",
    expired: "info",
    invalid: "danger",
  };
  return typeMap[status] || "";
};

// 获取日志类型
const getLogType = (type) => {
  const typeMap = {
    system: "info",
    user: "warning",
    admin: "success",
    error: "danger",
  };
  return typeMap[type] || "info";
};

// 检查订单是否已验票
const isTicketChecked = (order) => {
  return order.eTickets?.every((ticket) => ticket.status === "used") || false;
};

// 处理验票
const handleCheckTicket = async (order) => {
  try {
    await ElMessageBox.confirm("确认为该订单进行验票操作？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    
    loading.value = true;
    // 调用验票API
    await axios.put(`/admin/orders/${order.id}/check-ticket`);
    
    ElMessage.success("验票成功");
    // 刷新订单详情
    showDetail(order);
    // 更新订单列表
    fetchData();
  } catch (error) {
    if (error !== "cancel") {
      console.error("验票失败：", error);
      ElMessage.error("验票失败，请稍后重试");
    }
  } finally {
    loading.value = false;
  }
};

// 初始化
onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.ticket-orders {
  padding: 20px;
  background-color: var(--el-bg-color-page);
  min-height: calc(100vh - 40px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid var(--el-border-color-light);
}

.header-actions {
  display: flex;
  align-items: center;
}

.search-form {
  background-color: var(--el-bg-color);
  padding: 24px;
  border-radius: 8px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.spot-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.spot-image {
  width: 120px;
  height: 80px;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.spot-detail {
  flex: 1;
  min-width: 0;
}

.spot-name {
  margin: 0 0 8px;
  font-size: 15px;
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.ticket-info {
  margin: 0;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.amount {
  font-weight: 500;
  color: var(--el-color-danger);
}

.pagination-container {
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid var(--el-border-color-light);
  display: flex;
  justify-content: flex-end;
}

.ml-2 {
  margin-left: 8px;
}

.mr-2 {
  margin-right: 8px;
}

/* 订单详情样式 */
.order-detail {
  padding: 20px;
}

.detail-section {
  margin-bottom: 24px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  margin: 0 0 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid var(--el-border-color-light);
}

.remark-content {
  padding: 12px;
  background-color: var(--el-fill-color-lighter);
  border-radius: 4px;
  color: var(--el-text-color-regular);
  line-height: 1.5;
}

:deep(.el-descriptions) {
  margin-bottom: 16px;
}

:deep(.el-descriptions__label) {
  width: 120px;
  justify-content: flex-end;
}

/* 模态框样式 */
:deep(.order-detail-modal) {
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.el-dialog) {
  margin: 0 !important;
  position: relative;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
}

:deep(.el-dialog__body) {
  flex: 1;
  padding: 0;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  margin: 0;
  padding: 20px;
  border-bottom: 1px solid var(--el-border-color-light);
}

:deep(.el-dialog__footer) {
  margin: 0;
  padding: 20px;
  border-top: 1px solid var(--el-border-color-light);
}

/* 滚动条样式优化 */
:deep(.el-scrollbar__bar) {
  z-index: 100;
}

:deep(.el-scrollbar__wrap) {
  max-height: inherit;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .ticket-orders {
    padding: 12px;
  }

  .search-form {
    padding: 16px;
  }

  .spot-image {
    width: 80px;
    height: 60px;
  }

  .spot-name {
    font-size: 14px;
  }

  :deep(.el-dialog) {
    width: 90% !important;
    max-height: 85vh;
  }
}

.spot-detail-info {
  display: flex;
  gap: 16px;
  align-items: center;
}

.spot-detail-image {
  width: 120px;
  height: 80px;
  border-radius: 4px;
  object-fit: cover;
}

.spot-detail-content {
  flex: 1;
}

.spot-name {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 8px;
}

.spot-address {
  color: var(--el-text-color-secondary);
  display: flex;
  align-items: center;
  gap: 4px;
}

.visitors-list {
  margin-top: 16px;
}

.visitors-list h5 {
  margin: 0 0 12px;
  font-size: 14px;
}

.e-tickets-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
  margin-top: 16px;
}

.e-ticket-card {
  border-radius: 4px;
  overflow: hidden;
}

.e-ticket-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.ticket-no {
  font-size: 13px;
  color: var(--el-text-color-secondary);
}

.e-ticket-qr {
  text-align: center;
  margin: 12px 0;
}

.e-ticket-qr .el-image {
  width: 120px;
  height: 120px;
}

.e-ticket-info {
  font-size: 13px;
  color: var(--el-text-color-secondary);
}

.e-ticket-info p {
  margin: 4px 0;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
}

.empty-text {
  font-size: 16px;
  font-weight: 500;
  color: var(--el-text-color-secondary);
  margin-bottom: 8px;
}

.empty-subtext {
  font-size: 14px;
  color: var(--el-text-color-secondary);
}
</style>
